<template>
  <view :class="['mes-box', boxClass]" :style="boxStyle">
    <!-- 消息展示区域 -->
    <view ref="messagesContainer" class="messages-container">
      <view v-for="(message, index) in messages" :key="message.id || index" class="message-item" :class="{ 'self-message': message.isSelf }">
        <img :src="message.avatar" alt="Avatar" class="avatar">
        <view class="message-content">
          <view class="user-info" :class="{ 'self-user-info': message.isSelf }">
            <span class="nickname">{{ message.nickname }}</span>
            <span class="level">Lv.{{ message.level }}</span>
            <!-- 替换为性别图片 -->
            <img :src="getGenderImage(message.gender)" alt="Gender" class="gender-image">
          </view>
          <view class="chat-bubble" v-if="message.code == 1">
            {{ message.content }}
          </view>
		  <!-- <view class="chat-bubble" v-else-if="message.code == 2">
		    赠送：{{ message.giftObj.name }}X1
			<Gift
				:imageUrl="message.giftObj.spritesImg" 
				frameCount="10"
			/>
		  </view> -->
        </view>
      </view>
    </view>
    <!-- 消息输入框和发送按钮 -->
    <view class="input-container">
      <input v-model="newMessage" placeholder="输入消息" class="message-input" @keydown.enter="sendMessage" ref="input"/>
      <view @click="sendMessage" class="send-button">发送</view>
    </view>
  </view>
</template>

<script>
// import Gift from "@/component/gift/Gift.vue";

export default {
  name: "WorldChatBox",
  props: {
    // 新增：接收订阅地址和发送地址的props
    subscribeTopic: {
      type: String,
      default: "/game/message"
    },
    sendTopic: {
      type: String,
      default: "/mori/message"
    },
    // 新增：支持通过props配置宽高和背景色
    boxWidth: {
      type: [String, Number],
      default: 220
    },
    boxHeight: {
      type: [String, Number],
      default: 260
    },
    boxBackgroundColor: {
      type: String,
      default: 'rgba(0, 0, 0, 0.5)'
    },
    boxClass: {
      type: String,
      default: ''
    }
  },
  // components:{
  // 	Gift
  // },
  computed: {
    boxStyle() {
      return {
        width: typeof this.boxWidth === 'number' ? `${this.boxWidth}px` : this.boxWidth,
        height: typeof this.boxHeight === 'number' ? `${this.boxHeight}px` : this.boxHeight,
        backgroundColor: this.boxBackgroundColor
      }
    }
  },
  data() {
    return {
      messages: [],
      newMessage: "",
      clientObj: client,
      scrollThreshold: 150,
      userInfo: null
    };
  },
  mounted() {
    this.userInfo = uni.getStorageSync("userInfo");
    this.initSocket();
    this.focusInput();
  },
  methods: {
    focusInput() {
      uni.createSelectorQuery().in(this).select('.message-input').node().exec((res) => {
        const inputRef = res[0]?.node;
        if (inputRef) inputRef.focus();
      });
    },
    initSocket() {
      console.log("初始化WebSocket连接");
      // 使用props中的订阅地址
      this.clientObj.subscribe(this.subscribeTopic, (msg) => {
        try {
          const data = JSON.parse(msg.body);
		  data.isSelf = this.userInfo?.id === data.id;
		  this.messages.push(data);
		  
		  //如果大于20条就移除之前的信息
		  if(this.messages.length > 25){
			  this.messages.shift();
		  }
		  
          this.$nextTick(() => this.scrollToBottomIfNeeded());
		  
        } catch (error) {
          console.error("解析消息失败:", error);
        }
      });
	  
	  // setInterval(()=>{
		 //  if(this.sendTopic == "/mori/officialLiveBroadcast"){
			//   let msg = {
			// 	  avatar: "https://fastly.picsum.photos/id/999/200/200.jpg?hmac=iwXALEStJtHL4Thxk_YbLNHNmjq9ZrIQYFUvtxndOaU",
			// 	  content: "喜欢主播的点点关注，卡个灯牌",
			// 	  gender: "男",
			// 	  id: "0",
			// 	  level: 999,
			// 	  nickname: "官方房管"
			//   }
			//   this.clientObj.send(this.sendTopic, {}, JSON.stringify(msg));
		 //  }
	  // },5000);
    },
    sendMessage() {
      const content = this.newMessage.trim();
      if (!content) return;

      const message = {
	    code: 1,
        id: this.userInfo?.id,
        avatar: this.userInfo?.avatar || '',
        nickname: this.userInfo?.nickname || '匿名用户',
        level: this.userInfo?.level || 1,
        gender: this.userInfo?.sex,
        content
      };
	  console.log(message);
      try {
        this.clientObj.send(this.sendTopic, {}, JSON.stringify(message));
        this.newMessage = "";
        this.$nextTick(() => this.scrollToBottomIfNeeded());
        setTimeout(() => this.focusInput(), 100);
      } catch (error) {
        console.error("发送消息失败:", error);
        // 可以添加失败提示
      }
    },
    getGenderImage(gender) {
      if (gender === "男") return "https://img.icons8.com/color/48/000000/male.png";
      if (gender === "女") return "https://img.icons8.com/color/48/000000/female.png";
      return "";
    },
    scrollToBottomIfNeeded() {
      const container = this.$refs.messagesContainer?.$el || this.$refs.messagesContainer;
      if (!container) return;

      const { scrollHeight, clientHeight, scrollTop } = container;
      const distanceFromBottom = scrollHeight - scrollTop - clientHeight;

      if (distanceFromBottom <= this.scrollThreshold) {
        container.scrollTop = scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.mes-box {
  padding: 10px;
  color: #000;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  position: relative;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE 和 Edge */
  scrollbar-width: none; /* Firefox */
}

/* 隐藏 Chrome、Safari 和 Opera 的滚动条 */
.messages-container::-webkit-scrollbar {
  display: none;
}

.message-item {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.self-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  margin: 0 6px;
}

.message-content {
  max-width: 70%;
}

.user-info {
  display: flex;
  align-items: center;
  font-size: 9px;
  color: #ccc;
}

.self-user-info {
  justify-content: flex-end;
}

.nickname {
  font-weight: bold;
  margin-right: 4px;
  /* 让昵称不影响气泡宽度 */
  word-break: break-all; 
}

.level {
  margin-right: 4px;
}

.gender-image {
  width: 12px;
  height: 12px;
  margin-left: 4px;
}

.chat-bubble {
  background-color: rgba(52, 152, 219, 0.8); /* 半透明背景色 */
  color: white;
  padding: 4px 8px;
  border-radius: 6px;
  position: relative;
  margin-top: 2px;
  font-size: 10px;
  word-break: break-word; /* 添加此样式让中英文正常换行 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
}

.self-message .chat-bubble {
  background-color: rgba(46, 204, 113, 0.8); /* 半透明背景色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
}

.input-container {
  display: flex;
  margin-top: 4px;
}

.message-input {
  flex: 1;
  padding: 2px 4px;
  border: none;
  border-radius: 3px;
  margin-right: 4px;
  font-size: 10px;
}

.send-button {
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 2px 8px;
  font-size: 10px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #2980b9;
}
</style>    